﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using CLEX.Service.DataContracts;

namespace CLEX.Client.Metro.ViewModel.Home
{
    public class TableListVM : VMBase
    {
        private readonly IFacade facade;
        private readonly IPopupService popup;
        private readonly UserData user;
        private readonly DatabaseData database;
        private readonly ReadOnlyCollection<TableData> tables;
        private readonly RelayCommand explore;
        private readonly RelayCommand cancel;
        private TableData selectedTable;

        public IEnumerable<TableData> Tables
        {
            get { return tables; }
        }

        public TableData SelectedTable
        {
            get { return selectedTable; }
            set
            {
                if (selectedTable != value)
                {
                    selectedTable = value;
                    RaisePropertyChanged("SelectedTable");
                    cancel.RaiseCanExecuteChanged();
                    explore.RaiseCanExecuteChanged();
                }
            }
        }

        public ICommand Explore
        {
            get { return explore; }
        }

        public ICommand Cancel
        {
            get { return cancel; }
        }

        public TableListVM(IFacade facade, IPopupService popup, UserData user, DatabaseData database)
        {
            this.facade = facade;
            this.popup = popup;
            this.user = user;
            this.database = database;
            this.tables = new ReadOnlyCollection<TableData>(facade.GetSchema(database.ConnectionString).OrderBy(p => p.Catalog).ThenBy(p => p.Schema).ThenBy(p => p.Name).ToList());
            this.explore = new RelayCommand(DoExplore, CanExplore);
            this.cancel = new RelayCommand(DoBack);
            selectedTable = tables.FirstOrDefault();
        }

        private void DoBack()
        {
            popup.ClosePopup();
        }

        private void DoExplore()
        {
            try
            {
                facade.GoToLattice(user, database, selectedTable);
            }
            catch (Exception ex)
            {
                facade.ShowUnexpectedError("Unable to explore database.", ex.Message);
            }
            popup.ClosePopup();
        }

        private bool CanExplore()
        {
            return selectedTable != null;
        }
    }
}
